﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NEXEntidad;
using System.Text;
using Jayrock.Json.Conversion;
using System.Text.RegularExpressions;

public partial class WebControls_Comentarios : System.Web.UI.UserControl
{
    #region Campos / Propiedades

    private ComentarioCollection fListaComentario;
    public ComentarioCollection ListaComentario
    {
        get { return fListaComentario; }
        set { fListaComentario = value; }
    }

    public String Descripcion
    {
        get { return txtComentario.Text; }
        set { txtComentario.Text = value; }
    }

    //private int fIdLibro;
    //public int IdLibro
    //{
    //    get { return fIdLibro; }
    //    set { fIdLibro = value; }
    //}

    #endregion



    #region Eventos de Pagina
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (!this.IsPostBack)
        //{

        ComentarioCollection comentarios;
        StringBuilder sb = new StringBuilder();
        string detalle;
        string alias;
        string jsonComentarios;
        string sScript;
        comentarios = this.fListaComentario;

        if (comentarios != null && Request.QueryString["ajax"] == null)
        {
            if (comentarios.Count > 0)
            {
                sb.Append("[");
                foreach (Comentario unComentario in comentarios)
                {
                    sb.Append("{id: '" + unComentario.Id + "',");
                    detalle = unComentario.Descripcion.Replace("\"", "-");
                    detalle = detalle.Replace("\n", "<br>");
                    detalle = detalle.Replace("\r", "");
                    alias = unComentario.Usuario.Alias.Replace("'\"", "-");
                    sb.Append("detalle: '" + detalle + "',");
                    sb.Append("alias: '" + alias + "',");
                    sb.Append("fecha: '" + ((DateTime)unComentario.Fecha).ToString("dd/MM/yyyy") + "'");

                    sb.Append("},");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("]");

                jsonComentarios = JsonConvert.ExportToString(sb.ToString());
                jsonComentarios = RemoveAccentsWithRegEx(jsonComentarios);
                sScript = "var gLista; \n";
                sScript += "$(document).ready(function() {  \n";
                sScript += " var listaComentarios = eval(" + jsonComentarios + "); \n";
                sScript += " var listaAcotada;  \n";
                sScript += " gLista = eval(" + jsonComentarios + "); \n";
                //sScript += " alert(eval(listaComentarios)); \n";
                sScript += " if (eval(listaComentarios[0]).length > 5)  \n";
                sScript += "    listaAcotada = eval(listaComentarios[0]).slice(0,5);  \n";
                sScript += " else  \n";
                sScript += "    listaAcotada = eval(listaComentarios[0]); \n";
                sScript += " $('#tablaComentarios').fillTemplate(listaAcotada); \n";
                sScript += " if (eval(listaComentarios[0]).length > 0) \n";
                sScript += "     $('#tablaComentarios').show(); \n";
                sScript += "}); \n";

                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ConterScript", sScript, true);
            }
            else
            {

                sScript = "$(document).ready(function() { ";
                sScript += " $('#tablaComentarios').hide();";
                sScript += "});";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ConterScript", sScript, true);
            }
        }
        //}
    }
    public static string RemoveAccentsWithRegEx(string inputString)
    {
        Regex replace_a_Accents = new Regex("[á|à|ä|â]", RegexOptions.Compiled);
        Regex replace_e_Accents = new Regex("[é|è|ë|ê]", RegexOptions.Compiled);
        Regex replace_i_Accents = new Regex("[í|ì|ï|î]", RegexOptions.Compiled);
        Regex replace_o_Accents = new Regex("[ó|ò|ö|ô]", RegexOptions.Compiled);
        Regex replace_u_Accents = new Regex("[ú|ù|ü|û]", RegexOptions.Compiled);
        inputString = replace_a_Accents.Replace(inputString, "a");
        inputString = replace_e_Accents.Replace(inputString, "e");
        inputString = replace_i_Accents.Replace(inputString, "i");
        inputString = replace_o_Accents.Replace(inputString, "o");
        inputString = replace_u_Accents.Replace(inputString, "u");
        return inputString;
    }
    protected void btnEnviar_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            int idLibro;
            Comentario unComentario = new Comentario();
            Usuario usuarioLogueado;
            if (Page.User.Identity.IsAuthenticated)
            {
                usuarioLogueado = ((Usuario)Session["Usuario"]);
                idLibro = Convert.ToInt32(((HiddenField)this.Parent.FindControl("hdnIdLibro")).Value);

                unComentario.Usuario = usuarioLogueado;
                unComentario.Libro = new Libro(idLibro);
                unComentario.Descripcion = txtComentario.Text;
                unComentario.Fecha = DateTime.Now;
                unComentario.EsInsert = true;
                unComentario.Salvar();
                txtComentario.Text = "";

                //Repeater1.DataSource = Comentario.Listar(idLibro, true);
                //Repeater1.DataBind();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnVerTodos_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            int idLibro;
            idLibro = Convert.ToInt32(((HiddenField)this.Parent.FindControl("hdnIdLibro")).Value);
            //Repeater1.DataSource = Comentario.Listar(idLibro, false);
            //Repeater1.DataBind();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    #endregion

}
